/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.rest;

import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.Image;
import me.zhengjie.modules.system.domain.MarkedJson;
import me.zhengjie.modules.system.domain.TaskMark;
import me.zhengjie.modules.system.repository.TaskMarkRepository;
import me.zhengjie.modules.system.service.ImageService;
import me.zhengjie.modules.system.service.MarkedJsonService;
import me.zhengjie.modules.system.service.TaskMarkService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.ImageMapper;
import me.zhengjie.modules.system.service.mapstruct.TaskMarkMapper;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;

/**
 * @website https://el-admin.vip
 * @author fzuir
 * @date 2021-01-20
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "api/json管理")
@RequestMapping("/api/markedJson")
public class MarkedJsonController {

    private final MarkedJsonService markedJsonService;
    private final ImageService imageService;
    private final ImageMapper imageMapper;
    private final TaskMarkService taskMarkService;
    private final TaskMarkMapper taskMarkMapper;
    private final TaskMarkRepository taskMarkRepository;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('markedJson:list')")
    public void download(HttpServletResponse response, MarkedJsonQueryCriteria criteria) throws IOException {
        markedJsonService.download(markedJsonService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询api/json")
    @ApiOperation("查询api/json")
    @PreAuthorize("@el.check('markedJson:list')")
    public ResponseEntity<Object> query(MarkedJsonQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(markedJsonService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping(value = "/checkImage")
    @Log("审核图片")
    @ApiOperation("审核图片")
    public ResponseEntity<Object> checkImage(@RequestBody Map<String,Long> imageDetail){
        System.out.println(imageDetail);
        if (imageDetail.get("pass")!=0){            //通过
            Integer alreayPass = 0;
            Integer hasFail = 0;
            ImageQueryCriteria imageQueryCriteria = new ImageQueryCriteria();
            imageQueryCriteria.setImageId(imageDetail.get("imageId"));
            List<ImageDto> imageDtos = imageService.queryAll(imageQueryCriteria);
            Image image = imageMapper.toEntity(imageDtos.get(0));
            if (image.getStatus()==4)  alreayPass=1;//该图片已经被通过
            image.setStatus((long) 4);
            imageService.update(image);
            MarkedJson markedJson = new MarkedJson();
            markedJson.setNumBox(image.getNumBox());
            markedJson.setImage(image);
            markedJson.setResultPath(image.getResultPath());
            markedJson.setStatus((long) 4);
            Optional<TaskMark> markTaskId = taskMarkRepository.findById(Math.toIntExact(imageDetail.get("markTaskId")));
            Integer passCount = 0;
            for (int i = 0; i < markTaskId.get().getImages().size(); i++) {
                if (markTaskId.get().getImages().get(i).getStatus()== Long.valueOf(4)) passCount++;
                if (markTaskId.get().getImages().get(i).getStatus()== Long.valueOf(0)) hasFail=1;
            }
            if (passCount == markTaskId.get().getImages().size()) markTaskId.get().setStatus((long) 5);
            else if(passCount!=0) markTaskId.get().setStatus((long) 4);
            if (hasFail==1) markTaskId.get().setStatus(Long.valueOf(0));    //如果有未通过图片，任务状态设为0
            markedJson.setTaskMark(markTaskId.get());
            markedJson.setUser(markTaskId.get().getUsers().get(0));
            markedJsonService.create(markedJson);
            //更新任务表
            Optional<TaskMark> markTaskID = taskMarkRepository.findById(Math.toIntExact(imageDetail.get("markTaskId")));
            TaskMark taskMark = markTaskID.get();
            if (alreayPass==0) taskMark.setNumChecked(taskMark.getNumChecked()+1);
            // 都审核完成 则任务审核通过
            if(taskMark.getNumChecked() == taskMark.getNumImage()){
                taskMark.setStatus(Long.valueOf(5));
            }
            //如果该图片已经被通过
            taskMarkService.update(taskMark);
        }else {
            ImageQueryCriteria imageQueryCriteria = new ImageQueryCriteria();
            imageQueryCriteria.setImageId(imageDetail.get("imageId"));
            List<ImageDto> imageDtos = imageService.queryAll(imageQueryCriteria);
            Image image = imageMapper.toEntity(imageDtos.get(0));
            long pastImageStatus = image.getStatus();
            image.setStatus((long) 0);
            imageService.update(image);
            Optional<TaskMark> markTaskId = taskMarkRepository.findById(Math.toIntExact(imageDetail.get("markTaskId")));
            markTaskId.get().setStatus((long) 0);
            if (imageDtos.get(0).getStatus()==4) markTaskId.get().setNumChecked(markTaskId.get().getNumChecked()-1);
//            markTaskId.get().setNumFinish(markTaskId.get().getNumFinish()+1);
            taskMarkService.update(markTaskId.get());
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping(value = "/checkTask")
    @Log("审核任务")
    @ApiOperation("审核任务")
    public ResponseEntity<Object> checkTask(@RequestBody Map<String,Long> data){
        Long imageStatus = (long) 0;
        Long taskStatus = (long) 0;
        if(data.get("pass") == 1){
            imageStatus = (long) 4;
            taskStatus = (long) 5;
        }
        Optional<TaskMark> taskMarks = taskMarkRepository.findById(Math.toIntExact(data.get("markTaskId")));
        TaskMark taskMark = taskMarks.get();
        List<Image> imageList = taskMark.getImages();
        for(Image i : imageList){
            // 更新图片表
            i.setStatus(imageStatus);
            imageService.update(i);
        }
        // 更新任务表
        taskMark.setStatus(taskStatus);
        taskMarkService.update(taskMark);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping
    @Log("新增api/json")
    @ApiOperation("新增api/json")
    @PreAuthorize("@el.check('markedJson:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody MarkedJson resources){
        return new ResponseEntity<>(markedJsonService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改api/json")
    @ApiOperation("修改api/json")
    @PreAuthorize("@el.check('markedJson:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody MarkedJson resources){
        markedJsonService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除api/json")
    @ApiOperation("删除api/json")
    @PreAuthorize("@el.check('markedJson:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        markedJsonService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
